#!/bin/bash

# macOS 12和14应用目录共享设置脚本
# 版本: 1.0

# 彩色输出函数
print_green() { printf "\033[0;32m%s\033[0m\n" "$1"; }
print_yellow() { printf "\033[0;33m%s\033[0m\n" "$1"; }
print_red() { printf "\033[0;31m%s\033[0m\n" "$1"; }
print_blue() { printf "\033[0;34m%s\033[0m\n" "$1"; }

# 基本设置
MACOS14_VOLUME="/Volumes/Sun"  # 14系统卷名，已修正为Sun
MACOS14_APPS="$MACOS14_VOLUME/Applications"
BACKUP_DIR="$HOME/.mac_sync/backup"  # 修改为本地备份以避免权限问题
SYSTEM_APPS_BACKUP="$BACKUP_DIR/MacOS12SystemApps"
LOG_DIR="$HOME/.mac_sync/logs"
LOG_FILE="$LOG_DIR/setup_apps_$(date +%Y%m%d-%H%M%S).log"

# 创建必要目录
mkdir -p "$BACKUP_DIR"
mkdir -p "$SYSTEM_APPS_BACKUP"
mkdir -p "$LOG_DIR"

# 日志函数
log_message() {
    echo "[$(date +%Y-%m-%d\ %H:%M:%S)] $1" | tee -a "$LOG_FILE"
}

log_message "开始设置应用目录共享 - $(sw_vers -productVersion)"
log_message "========================================"

# 检查是否在macOS 12系统上运行
check_macos_version() {
    local version=$(sw_vers -productVersion | cut -d. -f1)
    if [[ "$version" != "12" ]]; then
        print_yellow "警告: 当前系统版本为 macOS $version，非macOS 12"
        log_message "警告: 检测到非macOS 12系统 (${version})"
        print_yellow "是否继续？(y/n)"
        read -n 1 answer
        if [[ "$answer" != "y" ]]; then
            log_message "用户选择退出"
            exit 1
        fi
    fi
    log_message "系统版本检查完成"
}

# 确保14系统分区已挂载
ensure_macos14_mounted() {
    if [ ! -d "$MACOS14_VOLUME" ]; then
        print_red "错误: 无法访问macOS 14系统卷 ($MACOS14_VOLUME)"
        print_yellow "请确保macOS 14系统卷已挂载，然后重试"
        log_message "错误: macOS 14系统卷未挂载"
        
        # 尝试挂载分区
        print_yellow "尝试自动挂载..."
        # 获取所有可用分区
        diskutil list | grep -i "Sun" | while read line; do
            local disk=$(echo $line | awk '{print $NF}')
            log_message "尝试挂载: $disk"
            diskutil mount "$disk"
            if [ -d "$MACOS14_VOLUME" ]; then
                print_green "成功挂载macOS 14系统卷"
                log_message "成功挂载macOS 14系统卷"
                break
            fi
        done
        
        # 再次检查
        if [ ! -d "$MACOS14_VOLUME" ]; then
            log_message "挂载尝试失败，退出"
            exit 1
        fi
    fi
    
    if [ ! -d "$MACOS14_APPS" ]; then
        print_red "错误: 无法找到macOS 14应用目录 ($MACOS14_APPS)"
        log_message "错误: macOS 14应用目录未找到"
        exit 1
    fi
    
    log_message "确认macOS 14系统卷已挂载且应用目录可访问"
}

# 配置自动挂载
configure_automount() {
    print_blue "配置自动挂载macOS 14系统卷..."
    
    # 获取14系统卷的UUID
    local uuid=$(diskutil info "$MACOS14_VOLUME" | grep "Volume UUID" | awk '{print $3}')
    
    if [ -z "$uuid" ]; then
        print_yellow "警告: 无法获取卷UUID，尝试使用设备标识符"
        local device=$(diskutil info "$MACOS14_VOLUME" | grep "Device Node" | awk '{print $3}')
        
        if [ -z "$device" ]; then
            print_red "错误: 无法获取卷信息"
            log_message "错误: 无法获取macOS 14卷信息"
            return 1
        fi
        
        log_message "使用设备标识符: $device"
    else
        log_message "使用卷UUID: $uuid"
    fi
    
    # 创建自动挂载plist文件
    cat > ~/Library/LaunchAgents/com.user.mount.macos14.plist << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.user.mount.macos14</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/sbin/diskutil</string>
        <string>mount</string>
EOF

    if [ -n "$uuid" ]; then
        cat >> ~/Library/LaunchAgents/com.user.mount.macos14.plist << EOF
        <string>$uuid</string>
EOF
    else
        cat >> ~/Library/LaunchAgents/com.user.mount.macos14.plist << EOF
        <string>$device</string>
EOF
    fi

    cat >> ~/Library/LaunchAgents/com.user.mount.macos14.plist << EOF
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>StandardErrorPath</key>
    <string>$LOG_DIR/mount_error.log</string>
    <key>StandardOutPath</key>
    <string>$LOG_DIR/mount_output.log</string>
</dict>
</plist>
EOF

    # 加载启动项
    launchctl unload ~/Library/LaunchAgents/com.user.mount.macos14.plist 2>/dev/null
    launchctl load -w ~/Library/LaunchAgents/com.user.mount.macos14.plist
    
    log_message "已配置自动挂载macOS 14系统卷"
    print_green "已配置自动挂载macOS 14系统卷"
}

# 系统应用列表
SYSTEM_APPS=(
    "App Store.app"
    "Automator.app"
    "Calculator.app"
    "Calendar.app"
    "Chess.app"
    "Contacts.app"
    "Dictionary.app"
    "FaceTime.app"
    "Home.app"
    "Image Capture.app"
    "Launchpad.app"
    "Mail.app"
    "Maps.app"
    "Messages.app"
    "Mission Control.app"
    "Music.app"
    "News.app"
    "Notes.app"
    "Photo Booth.app"
    "Photos.app"
    "Podcasts.app"
    "Preview.app"
    "QuickTime Player.app"
    "Reminders.app"
    "Safari.app"
    "Stickies.app"
    "Stocks.app"
    "System Information.app"
    "System Preferences.app"
    "TextEdit.app"
    "Time Machine.app"
    "TV.app"
    "Utilities"
    "Voice Memos.app"
    "Weather.app"
)

# 备份系统应用
backup_system_apps() {
    print_blue "备份macOS 12系统应用..."
    
    for app in "${SYSTEM_APPS[@]}"; do
        if [ -e "/Applications/$app" ] && [ ! -L "/Applications/$app" ]; then
            log_message "备份系统应用: $app"
            cp -R "/Applications/$app" "$SYSTEM_APPS_BACKUP/"
        fi
    done
    
    log_message "系统应用备份完成"
    print_green "系统应用备份完成"
}

# 设置应用目录
setup_applications_directory() {
    print_blue "开始设置应用目录..."
    
    # 检查当前应用目录状态
    if [ -L "/Applications" ]; then
        local current_link=$(readlink "/Applications")
        log_message "当前/Applications已经是符号链接，指向: $current_link"
        
        if [ "$current_link" == "$MACOS14_APPS" ]; then
            print_green "应用目录已经正确链接到macOS 14的应用目录"
            log_message "应用目录已经正确设置"
            return 0
        else
            print_yellow "重新配置应用目录链接..."
            sudo rm "/Applications"
        fi
    elif [ -d "/Applications" ]; then
        print_yellow "将现有应用目录重命名为/Applications.original..."
        log_message "重命名现有应用目录"
        sudo mv "/Applications" "/Applications.original"
    fi
    
    # 创建新的符号链接
    log_message "创建符号链接: /Applications -> $MACOS14_APPS"
    sudo ln -s "$MACOS14_APPS" "/Applications"
    
    print_green "已将应用目录链接到macOS 14系统"
    log_message "应用目录链接设置完成"
}

# 恢复系统应用
restore_system_apps() {
    print_blue "恢复macOS 12系统应用..."
    
    # 确保原始目录存在
    if [ ! -d "/Applications.original" ]; then
        log_message "创建原始应用目录"
        sudo mkdir -p "/Applications.original"
    fi
    
    # 创建系统应用处理脚本
    cat > ~/.mac_sync/scripts/handle_system_apps.sh << EOF
#!/bin/bash

LOG_FILE="$LOG_DIR/system_apps_\$(date +%Y%m%d).log"

log() {
    echo "[\$(date +%Y-%m-%d\ %H:%M:%S)] \$1" >> "\$LOG_FILE"
}

log "开始处理系统应用"

# 系统应用列表
SYSTEM_APPS=(
$(for app in "${SYSTEM_APPS[@]}"; do echo "    \"$app\""; done)
)

# 从备份恢复系统应用到原始目录
for app in "\${SYSTEM_APPS[@]}"; do
    if [ -e "$SYSTEM_APPS_BACKUP/\$app" ] && [ ! -e "/Applications.original/\$app" ]; then
        log "恢复系统应用到原始目录: \$app"
        sudo cp -R "$SYSTEM_APPS_BACKUP/\$app" "/Applications.original/"
    fi
done

# 创建系统应用覆盖链接
for app in "\${SYSTEM_APPS[@]}"; do
    if [ -e "/Applications.original/\$app" ]; then
        if [ -e "/Applications/\$app" ] && [ ! -L "/Applications/\$app" ]; then
            log "替换标准应用为链接: \$app"
            sudo rm -rf "/Applications/\$app.temp" 2>/dev/null
            sudo mv "/Applications/\$app" "/Applications/\$app.temp" 2>/dev/null
            sudo ln -sf "/Applications.original/\$app" "/Applications/\$app"
            sudo rm -rf "/Applications/\$app.temp" 2>/dev/null
        elif [ ! -e "/Applications/\$app" ]; then
            log "创建系统应用链接: \$app"
            sudo ln -sf "/Applications.original/\$app" "/Applications/\$app"
        fi
    fi
done

log "系统应用处理完成"
EOF
    
    # 设置脚本权限
    chmod +x ~/.mac_sync/scripts/handle_system_apps.sh
    
    # 运行系统应用处理脚本
    bash ~/.mac_sync/scripts/handle_system_apps.sh
    
    # 设置系统应用处理启动项
    cat > ~/Library/LaunchAgents/com.user.systemapps.plist << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.user.systemapps</string>
    <key>ProgramArguments</key>
    <array>
        <string>$(realpath ~/.mac_sync/scripts/handle_system_apps.sh)</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>StandardErrorPath</key>
    <string>$LOG_DIR/system_apps_error.log</string>
    <key>StandardOutPath</key>
    <string>$LOG_DIR/system_apps_output.log</string>
</dict>
</plist>
EOF
    
    # 加载启动项
    launchctl unload ~/Library/LaunchAgents/com.user.systemapps.plist 2>/dev/null
    launchctl load -w ~/Library/LaunchAgents/com.user.systemapps.plist
    
    log_message "系统应用恢复和启动项设置完成"
    print_green "系统应用处理设置完成"
}

# 创建健康检查脚本
create_health_check() {
    print_blue "创建链接健康检查脚本..."
    
    cat > ~/.mac_sync/scripts/check_app_links.sh << EOF
#!/bin/bash

LOG_FILE="$LOG_DIR/health_check_\$(date +%Y%m%d).log"

echo "[\$(date +%Y-%m-%d\ %H:%M:%S)] 开始健康检查" >> "\$LOG_FILE"

# 检查macOS 14系统卷是否挂载
if [ ! -d "$MACOS14_VOLUME" ]; then
    echo "[\$(date +%Y-%m-%d\ %H:%M:%S)] 错误: macOS 14系统卷未挂载" >> "\$LOG_FILE"
    osascript -e 'display notification "macOS 14系统卷未挂载，部分应用可能无法使用" with title "应用访问警告"'
    diskutil mount "$MACOS14_VOLUME" >> "\$LOG_FILE" 2>&1
fi

# 检查应用目录链接
if [ ! -L "/Applications" ]; then
    echo "[\$(date +%Y-%m-%d\ %H:%M:%S)] 错误: 应用目录不是符号链接" >> "\$LOG_FILE"
    osascript -e 'display notification "应用目录链接丢失，请运行设置脚本修复" with title "应用访问错误"'
else
    link_target=\$(readlink "/Applications")
    if [ "\$link_target" != "$MACOS14_APPS" ]; then
        echo "[\$(date +%Y-%m-%d\ %H:%M:%S)] 错误: 应用目录链接指向错误位置 (\$link_target)" >> "\$LOG_FILE"
    fi
fi

# 检查损坏的链接
broken_links=\$(find "/Applications" -maxdepth 1 -type l -exec test ! -e {} \; -print | wc -l)
if [ \$broken_links -gt 0 ]; then
    echo "[\$(date +%Y-%m-%d\ %H:%M:%S)] 警告: 发现\$broken_links个损坏的链接" >> "\$LOG_FILE"
    find "/Applications" -maxdepth 1 -type l -exec test ! -e {} \; -print >> "\$LOG_FILE"
fi

# 检查系统应用链接
for app in "/Applications"/*.app; do
    app_name=\$(basename "\$app")
    if [ -e "/Applications.original/\$app_name" ] && [ ! -L "\$app" ]; then
        echo "[\$(date +%Y-%m-%d\ %H:%M:%S)] 警告: 系统应用\$app_name没有使用本地版本" >> "\$LOG_FILE"
    fi
done

echo "[\$(date +%Y-%m-%d\ %H:%M:%S)] 健康检查完成" >> "\$LOG_FILE"
EOF
    
    # 设置脚本权限
    chmod +x ~/.mac_sync/scripts/check_app_links.sh
    
    # 设置健康检查启动项
    cat > ~/Library/LaunchAgents/com.user.apphealth.plist << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.user.apphealth</string>
    <key>ProgramArguments</key>
    <array>
        <string>$(realpath ~/.mac_sync/scripts/check_app_links.sh)</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>StartInterval</key>
    <integer>3600</integer>
    <key>StandardErrorPath</key>
    <string>$LOG_DIR/health_error.log</string>
    <key>StandardOutPath</key>
    <string>$LOG_DIR/health_output.log</string>
</dict>
</plist>
EOF
    
    # 加载启动项
    launchctl unload ~/Library/LaunchAgents/com.user.apphealth.plist 2>/dev/null
    launchctl load -w ~/Library/LaunchAgents/com.user.apphealth.plist
    
    log_message "健康检查脚本和启动项设置完成"
    print_green "健康检查设置完成"
}

# 主函数
main() {
    print_blue "===== 开始配置macOS 12使用14系统应用目录 ====="
    
    # 检查系统版本
    check_macos_version
    
    # 确保14系统卷已挂载
    ensure_macos14_mounted
    
    # 配置自动挂载
    configure_automount
    
    # 备份系统应用
    backup_system_apps
    
    # 设置应用目录
    setup_applications_directory
    
    # 恢复系统应用
    restore_system_apps
    
    # 创建健康检查
    create_health_check
    
    print_green "===== 配置完成 ====="
    log_message "配置全部完成"
}

# 执行主函数
main

echo ""
echo "配置总结:"
echo "1. 应用目录已链接到macOS 14系统"
echo "2. 系统应用已保留macOS 12版本"
echo "3. 已设置自动挂载macOS 14系统卷"
echo "4. 已创建健康检查脚本定期监控"
echo ""
echo "日志文件位置: $LOG_FILE" 